<template>
	<div>
		<!--头部：分类  增加 -->
		<div class="filter-container"><el-button type="primary" :icon="CirclePlus" @click="handleAdd">新增</el-button></div>

		<!-- 数据列表 编辑 删除 -->
		<div class="list-container">
			<el-table :data="dataList" fit highlight-current-row>
				<el-table-column prop="id" label="ID" width="60" align="center"></el-table-column>
				<el-table-column prop="name" label="名称" width="180"></el-table-column>
				<el-table-column prop="sort" label="排序" width="60" align="center"></el-table-column>
				<el-table-column label="图片" align="center" width="80">
					<template #default="scope">
						<el-image :src="$fullUrl(scope.row.img)" :preview-src-list="[$fullUrl(scope.row.img)]" preview-teleported></el-image>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="180" align="center">
					<template #default="{row}">
						<el-button link type="primary" :icon="Edit" @click="handleUpdate(row.id)">编辑</el-button>
						<el-button link type="danger" :icon="Delete" @click="handleDelete(row.id)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<!-- 数据量不多，这里就不进行分页处理了 -->
		</div>

		<!-- 编辑弹出框 -->
		<category-edit v-if="editDialogVisible" ref="editDialogRef" @refreshDataList="loadDataList" />
	</div>
</template>

<script setup>
import CategoryEdit from './components/CategoryEdit.vue';
import * as CategoryAPI from '@/api/category.js';
import { ref, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { CirclePlus, Edit, Delete } from '@element-plus/icons-vue';
//列表数据
const dataList = ref([]);
//编辑框是否显示
const editDialogVisible = ref(false);
// 生命周期
onMounted(() => {
	// 获取数据
	loadDataList();
});
// 获取列表数据
const loadDataList = async () => {
	const result = await CategoryAPI.getList();
	dataList.value = result.data;
	console.log(result);
};

// 删除操作
const handleDelete = (id) => {
	// 二次确认删除
	ElMessageBox.confirm('确定要删除吗？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(async () => {
		// 选择了确认，则删除后端数据库中的记录		
		await CategoryAPI.deleteById(id);
		loadDataList(); //刷新列表中的记录
		ElMessage.success('删除成功');
	});
};

// 声明模板中DOM元素的引用, 必须和模板里的 ref 同名
const editDialogRef = ref(null);

// 编辑
const handleUpdate = async (id) => {	
	editDialogVisible.value = true;
	await nextTick();
	editDialogRef.value.init(id);
};

// 增加
const handleAdd = async () => {
	editDialogVisible.value = true;
	await nextTick();
	editDialogRef.value.init();
};
</script>

<style></style>
